package com.qidian.mespro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mespro.mapper.ProcessMapper;
import com.qidian.mespro.mapper.WorkflowMapper;
import com.qidian.mespro.service.WorkflowService;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.Workflow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ author: 周晓轩
 * @ company 起点编程
 * @ time: 2025/9/18 - 16:59
 * @ Description:
 */
@Service
public class WorkflowServiceImpl implements WorkflowService {

    @Autowired
    private WorkflowMapper workflowMapper;

    @Autowired
    private ProcessMapper processMapper;

    @Override
    public Result<PageInfo<Workflow>> WorkflowList(Workflow workflow, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Workflow> workflows = workflowMapper.workflowList(workflow);
        return Result.success(new PageInfo<>(workflows));
    }

    @Override
    public Result<Workflow> addWorkflow(Workflow workflow) {
        Result<Workflow> existResult = selectWorkflowByCode(workflow.getWorkflowCode());
        if (existResult.isSuccess() && existResult.getData() != null) {
            return Result.error("工艺编码已存在，新增失败");
        }
        return workflowMapper.addWorkflow(workflow)== 1?Result.success(workflow):Result.error("保存失败");
    }

    @Override
    public Result<Workflow> selectWorkflowByCode(String code) {
        return  Result.success(workflowMapper.selectWorkflowByCode(code));
    }

    @Override
    public Result updateWorkflowById(Workflow workflow) {
        Result<Workflow> existResult = selectWorkflowByCode(workflow.getWorkflowCode());
        if (existResult.isSuccess() && existResult.getData() != null) {
            if (!existResult.getData().getId().equals(workflow.getId())) {
                return Result.error("工艺编码已被占用，请更换");
            }
        }
        return workflowMapper.updateWorkflowById(workflow)== 1 ? Result.success():Result.error("编辑失败");
    }

    @Override
    public Result deleteWorkflowById(Long id) {
        return workflowMapper.deleteWorkflowById(id)== 1?Result.success():Result.error("删除失败");
    }

    @Override
    public Result batchDelete(Long[] ids) {
        return workflowMapper.batchDelete(ids) > 0?Result.success():Result.error("删除失败");
    }

    @Override
    public Result<List<Workflow>> selectListByMaterialCode(String code) {
        List<Workflow> workflows = workflowMapper.selectListByMatiralCode(code);
        workflows.forEach(workflow -> {
            workflow.setProcesses(processMapper.selectProcessByWorkflowId(workflow.getId()));
        });
        return Result.success(workflows);
    }
}
